#include "ODBC.h"
#include "ErrorCode.h"

// Constructor initializes the string chr_ds_name with the
// data source name.
odbc::odbc()
{

}

void odbc::Initialize(TCHAR * DSN_name)
{
	wcscpy_s(chr_ds_name,DSN_name);
}

// Allocate environment handle, allocate connection handle,
// connect to data source, and allocate statement handle.
int odbc::conn(TCHAR * UserName,TCHAR * UserPassword)
{
	SQLAllocEnv(&henv);
	SQLAllocConnect(henv,&hdbc);
	rc=SQLConnect(hdbc,chr_ds_name,SQL_NTS,(SQLTCHAR *)UserName,SQL_NTS,(SQLTCHAR *)UserPassword,SQL_NTS);

	// Deallocate handles, display error message, and exit.
	if (!MYSQLSUCCESS(rc))
	{
		SQLFreeEnv(henv);
		SQLFreeConnect(hdbc);
		error_out();
		return SQLConnError;
	}
	rc=SQLAllocStmt(hdbc,&hstmt);
	return Success;
}

// Execute SQL command with SQLExecDirect() odbc API.
int odbc::exec(TCHAR * cmdstr)
{
	rc=SQLExecDirect(hstmt,cmdstr,SQL_NTS);
	if (!MYSQLSUCCESS(rc))  //Error
	{
		OutputDebugString(TEXT("ODBC:Exec:Error_Out"));
		error_out();
		// Deallocate handles and disconnect.
		SQLFreeStmt(hstmt,SQL_DROP);
		SQLDisconnect(hdbc);
		SQLFreeConnect(hdbc);
		SQLFreeEnv(henv);
		return SQLExecError;
	}
	return Success;
}

// Free the statement handle, disconnect, free the connection handle, and
// free the environment handle.
void odbc::disconn(void)
{
	SQLFreeStmt(hstmt,SQL_DROP);
	SQLDisconnect(hdbc);
	SQLFreeConnect(hdbc);
	SQLFreeEnv(henv);
}

// Display error message in a message box that has an OK button.
void odbc::error_out(void)
{
	unsigned char szSQLSTATE[10];
	SDWORD nErr;
	unsigned char msg[SQL_MAX_MESSAGE_LENGTH+1];
	SWORD cbmsg;
	while(SQLErrorA(0,0,hstmt,szSQLSTATE,&nErr,msg,sizeof(msg),&cbmsg)==SQL_SUCCESS)
	{
		wsprintfA((char *)szData,"Error:\nSQLSTATE=%s,Native error=%ld,msg='%s'",szSQLSTATE,nErr,msg);
		//mbstowcs   (   pszMbyte,   pszXparent,   cchMaxBuf   );   
		//OutputDebugStringA(szSQLSTATE);
		OutputDebugString((const TCHAR *)szData);
	}
}